﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Business_EditBook : Frame.Pages.BasePage
{
    string SQLBookTables = @"select TableID,TableName,PCount,TRemark=Tables.Remark,
	                                Area.AreaName,State
                             from   BLI_BookDetail as Detail,
	                                BI_Tables as Tables,
	                                BI_Area as Area
                             where  Detail.Table_ID = Tables.TableID and
	                                Area.AreaID = Tables.Area_ID and
	                                BookNo=@bookNo";

    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!IsPostBack && !IsCallback)
        {
            Frame.Global.GlobalFunctions.SetGridView(gridView, false);
            gridView.SettingsText.ConfirmDelete = "确认要撤销预定这个桌台么？";
            string sqlstr = "select PeriodName=a.PeriodName + ' ' + BeginTime+'——'+EndTime,a.PeriodID from BI_ConsumePeriod a";
            using (SqlDataReader dr = Frame.Global.GlobalSqlHelper.GetSQLDataReader(sqlstr))
            {
                for (; dr.Read(); )
                {
                    Edit_Perid_ID.Items.Add(dr["PeriodName"].ToString(), dr["PeriodID"]);
                }
            }
            if (Book == null && Action == "new")//修改
            {
                //this.BtnDel.Visible = false;
                m_Book = new DAL.BLI_Book();
                m_Book.AddTime = Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.AddTime;
                m_Book.BookNo = Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.BookNo;
                m_Book.BookDate = Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.BookDate;
                if (this.ConsumerID > 0)
                {
                    m_Book.Consumer_ID = this.ConsumerID;
                }

                m_Book.ContractName = this.ConsumerDetail == null ? string.Empty : this.ConsumerDetail.CName;
                m_Book.ContractPhoneNum = this.ConsumerDetail == null ? string.Empty : this.ConsumerDetail.PhoneNum;
                m_Book.Money = Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.Money;
                m_Book.Perid_ID = Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.Perid_ID;
                m_Book.BookType = 0;
                m_Book.PeopleNumber = 0;
            }
            this.Edit_AddTime.Text = Book.AddTime.ToString();
            this.Edit_BookDate.Text = Book.BookDate;
            this.Edit_BookNo.Text = Book.BookNo;
            this.Edit_BookType.SelectedItem.Value = Book.BookType;
            Edit_ContractName.Text = Book.ContractName;
            Edit_ContractPhoneNum.Text = Book.ContractPhoneNum;
            Edit_Money.Text = Book.Money.ToString("f2");
            Edit_Perid_ID.Value = Book.Perid_ID;
            Edit_SalesPerson.Text = Book.SalesPerson;
            Edit_PeopleNumber.Text = Book.PeopleNumber.ToString();
            if (ConsumerDetail != null)
            {
                //Backlink.NavigateUrl = (Frame.Pages.RefrenceContext<DAL.BI_Consumer>.Current == null ? string.Empty : Frame.Pages.RefrenceContext<DAL.BI_Consumer>.Current.BackUrl);
                WebUtility.MappingConsumerView(Detailpanel, ConsumerDetail);
            }
            else
            {
                this.Detailpanel.Visible = false;
            }
        }

        GVDataBind();
    }

    private void GVDataBind()
    {
        gridView.DataSource = Frame.Global.GlobalSqlHelper.ExecuteSQLToDataTable(SQLBookTables, new SqlParameter("@bookNo", BookNo));
        gridView.DataBind();
    }

    protected override string ActionID
    {
        get { return "0"; }
    }

    int m_ConsumerID = -1;
    protected int ConsumerID
    {
        get
        {
            if (Request.QueryString["Consumerid"] != null)
            {
                bool isint = int.TryParse(Request.QueryString["Consumerid"], out  m_ConsumerID);
                return m_ConsumerID;
            }
            if (Book.Consumer_ID != null)
            {
                m_ConsumerID = Book.Consumer_ID.Value;
                return m_ConsumerID;
            }
            return m_ConsumerID;
        }
    }
    DAL.BI_Consumer m_ConsumerDetail = null;
    public DAL.BI_Consumer ConsumerDetail
    {
        get
        {
            if (ConsumerID > 0 && m_ConsumerDetail == null)
            {
                using (DAL.CMSDALDataContext DataSession = new DAL.CMSDALDataContext())
                {
                    m_ConsumerDetail = DataSession.BI_Consumer.FirstOrDefault(o => o.ConsumerID == ConsumerID);
                }
            }
            return m_ConsumerDetail;

        }
    }

    protected DAL.CMSDALDataContext DataSession = new DAL.CMSDALDataContext();
    string m_BookNo = string.Empty;
    public string BookNo
    {
        get
        {
            m_BookNo = Request.QueryString["BookNo"] ?? string.Empty;
            return m_BookNo;
        }
    }
    DAL.BLI_Book m_Book = null;
    public DAL.BLI_Book Book
    {
        get
        {
            if (!string.IsNullOrEmpty(BookNo) && m_Book == null)
            {
                m_Book = DataSession.BLI_Book.FirstOrDefault(o => o.BookNo == BookNo);
            }
            return m_Book;
        }
    }

    public string Action
    {
        get
        {
            return Request.QueryString["BookNo"] ?? "new";
        }
    }
    protected void gridView_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        DAL.BLI_BookDetail detail = DataSession.BLI_BookDetail
            .FirstOrDefault(o => o.BookNo == BookNo && o.Table_ID == e.Keys["TableID"].ToString());
        detail.State = Convert.ToInt32(e.NewValues["State"]);
        DataSession.SubmitChanges();
        e.Cancel = true;
        gridView.CancelEdit();
        GVDataBind();
    }
    protected void gridView_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        DAL.BLI_BookDetail detail = DataSession.BLI_BookDetail
                .FirstOrDefault(o => o.BookNo == BookNo && o.Table_ID == e.Keys["TableID"].ToString());
        DataSession.BLI_BookDetail.DeleteOnSubmit(detail);
        DataSession.SubmitChanges();
        e.Cancel = true;
        GVDataBind();
    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        if (Book == null && Action == "new")//修改
        {
            m_Book = new DAL.BLI_Book();
        }
        m_Book.BookNo = Edit_BookNo.Text;
        if (ConsumerID > 0)
        {
            m_Book.Consumer_ID = ConsumerID;
        }
        m_Book.BookType = Convert.ToInt32(this.Edit_BookType.SelectedItem.Value);
        m_Book.ContractName = Edit_ContractName.Text;
        m_Book.ContractPhoneNum = Edit_ContractPhoneNum.Text;
        m_Book.Money = decimal.Parse(Edit_Money.Text);
        m_Book.Perid_ID = Convert.ToInt32(Edit_Perid_ID.SelectedItem.Value);
        m_Book.AddTime = DateTime.Now;
        m_Book.BookDate = Edit_BookDate.Date.ToShortDateString();
        //m_Book.BookType = Convert.ToInt32(Edit_BookType.Value);
        m_Book.Operator = CMSUser.Current.ID;
        m_Book.SalesPerson = Edit_SalesPerson.Text.Trim();
        m_Book.PeopleNumber = Int32.Parse(Edit_PeopleNumber.Text);
        if (Action == "new")//修改
        {
            DataSession.BLI_Book.InsertOnSubmit(m_Book);
        }

        //将预定信息插入或更新到餐饮系统数据库
        int count = WebUtility.InsertMast(m_Book);
        if (count > 0)
        {
            if (ConsumerDetail != null)
            {
                //获取短信模版
                using (SqlDataReader dr = Frame.Global.GlobalSqlHelper.GetSQLDataReader("select SMSContent,SMSClass_ID from BI_SMSLibrary where SMSLibraryID=(select Value from BI_SysSettings where SettingName='SMS_Book')"))
                {
                    if (dr.Read())
                    {
                        string content = dr["SMSContent"].ToString();
                        //修改内容
                        string newcontent = WebUtility.CreateMessage(content, m_Book, null, null);
                        //插入短信
                        WebUtility.InsertSMS((long)m_Book.Consumer_ID, DateTime.Now, newcontent, (int)dr["SMSClass_ID"]);
                    }
                }
            }
            DataSession.SubmitChanges();
            Frame.Global.GlobalFunctions.AlertToUrl("操作成功！", string.Format("EditBook.aspx?BookNo={0}", m_Book.BookNo));
        }
        else
        {
            Frame.Global.GlobalFunctions.Alert("操作失败！");
        }

    }
    protected void BtnCancel_Click(object sender, EventArgs e)
    {
        if (Action == "new")
        {
            DataSession.BLI_BookDetail.DeleteAllOnSubmit(DataSession.BLI_BookDetail.Where(o => o.BookNo == Frame.Pages.RefrenceContext<DAL.BLI_Book>.Current.Model.BookNo));
            DataSession.SubmitChanges();
        }
        if (ConsumerDetail != null)
        {
            Response.Redirect(string.Format("~/ConsumerManage/ConsumerQuick.aspx?Consumerid={0}&action=book", ConsumerID));
        }
        else
        {
            Response.Redirect("~/Business/TableView.aspx");
        }
    }
    protected void BtnDel_Click(object sender, EventArgs e)
    {
        if (ConsumerDetail != null)
        {
            //获取短信模版
            using (SqlDataReader dr = Frame.Global.GlobalSqlHelper.GetSQLDataReader("select SMSContent,SMSClass_ID from BI_SMSLibrary where SMSLibraryID=(select Value from BI_SysSettings where SettingName='SMS_Cancel')"))
            {
                if (dr.Read())
                {
                    string content = dr["SMSContent"].ToString();
                    //修改内容
                    string newcontent = WebUtility.CreateMessage(content, Book, null, null);
                    //插入短信
                    if (Book.Consumer_ID != null)
                    {
                        WebUtility.InsertSMS((long)Book.Consumer_ID, DateTime.Now, newcontent, (int)dr["SMSClass_ID"]);
                    }
                }
            }
        }

        DataSession.BLI_Book.DeleteOnSubmit(Book);
        DataSession.BLI_BookDetail.DeleteAllOnSubmit(DataSession.BLI_BookDetail.Where(o => o.BookNo == Book.BookNo));
        DataSession.SubmitChanges();
        if (ConsumerDetail != null)
        {
            Frame.Global.GlobalFunctions.AlertToUrl("取消成功！", string.Format("../ConsumerManage/ConsumerQuick.aspx?Consumerid={0}&action=book", ConsumerID));
        }
        else
        {
            Frame.Global.GlobalFunctions.AlertToUrl("取消成功！", "TableView.aspx");
        }
    }
    protected void btOK_Click(object sender, EventArgs e)
    {
        try
        {
            bool isNew = false;
            //判断是否已经结账过
            DAL.BLI_ConsumerHis con = DataSession.BLI_ConsumerHis.FirstOrDefault(o => o.BookNo == Action);
            if (con == null)
            {
                isNew = true;
                con = new DAL.BLI_ConsumerHis();
                con.BookNo = Action;
                con.Consumer_ID = ConsumerID;
                con.ConsumerDate = DateTime.Now;
                con.AddTime = DateTime.Now;
                con.Period_ID = (int)Edit_Perid_ID.SelectedItem.Value;
                con.TableCount = gridView.VisibleRowCount;
                con.Remark = "手动结账";
            }
            con.Money = Convert.ToDecimal(tbMoney.Text.Trim());
            if (isNew)
            {
                DataSession.BLI_ConsumerHis.InsertOnSubmit(con);
            }

            //更改预定桌位状态
            foreach (DAL.BLI_BookDetail item in DataSession.BLI_BookDetail.Where(o => o.BookNo == Action).ToList())
            {
                item.State = 4;
            }

            DataSession.SubmitChanges();
            btCancel.Text = "完成";
            Frame.Global.GlobalFunctions.Alert("手动结账成功!");
        }
        catch (Exception ex)
        {
            Frame.Global.GlobalFunctions.Alert("手动结账失败:" + ex + "!");
        }
    }
}